#include <Python.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
#include <locale.h>
#include <sys/wait.h>
#include <poll.h>
#include <fcntl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include <errno.h>
#include <pthread.h>
#include "sound.h"
#include "time.h"
#include "food.h"
#include "yolo.h"
#include "speak.h"
#include "sql.h"
#include "deep.h"
#include "cold.h"
#include "mqtt.h"
#include "aht20.h"

// 线程同步和状态管理
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t menu_cond = PTHREAD_COND_INITIALIZER;
pthread_cond_t deep_menu_cond = PTHREAD_COND_INITIALIZER;
char* global_user_preferences = NULL;

// 深度菜单生成函数
void* deep_menu_thread(void* arg) {
    while (1) {
        char* user_preferences = NULL;
        char* category = NULL;
        // 等待深度菜单请求
        pthread_mutex_lock(&mutex);
        while (global_user_preferences == NULL) {
            pthread_cond_wait(&deep_menu_cond, &mutex);
        }
        
        // 获取用户偏好
        user_preferences = strdup(global_user_preferences);
        global_user_preferences = NULL;
        pthread_mutex_unlock(&mutex);
        
        // 执行深度菜单生成
        printf("Generating deep menu for: %s\n", user_preferences);
        
        category = find_food(NULL);
        start_mqtt_publisher(1, true);
        if (category) {
            printf("Recognized category: %s\n", category);
        } else {
            printf("Failed to recognize category\n");
            category = strdup("unkown");
        }
        
        char* check_result = check_food(NULL);
        if (check_result) {
            printf("Food check result: %s\n", check_result);
            //menu_send(category, check_result);
        } else {
            check_result = strdup("unknown");
        }
        
        // 生成推荐菜品
        deep_main(category, user_preferences);
        printf("%s|%s|%d: deep_main ok\n", __FILE__, __func__, __LINE__);
        //if (recommended_dish) {
            //printf("Recommended dish: %s\n", recommended_dish);
            //food_send(recommended_dish, user_preferences);
            //food_write(recommended_dish, user_preferences);
            //free(recommended_dish);
        //} else {
            //food_send("识别错误", user_preferences);
        //}
        
        start_mqtt_publisher(0, true);
        // 清理资源
        free(category);
        if (strcmp(check_result, "error") != 0) free(check_result);
        free(user_preferences);
        remove(GARBAGE_FILE);
        
        // 避免连续调用占用资源
        sleep(1);
    }
    return NULL;
}

// 获取语音命令的线程函数
void* get_voice_thread(void* arg) {
    int sound_fd = -1;
    unsigned char work_result = 0;
    printf("%s|%s|%d: Starting voice thread\n", __FILE__, __func__, __LINE__);

    // 打开I2C设备
    if ((sound_fd = open("/dev/i2c-7", O_RDWR)) < 0) {
        perror("Failed to open voice I2C device");
        goto cleanup;
    }
 
    // 初始化语音模块
    if (set_voice_language(sound_fd, 0x00) < 0) {
        fprintf(stderr, "Voice module initialization failed\n");
        goto cleanup;
    }

    printf("Listening for voice commands...\n");

    while (1) {
        int ret = read_voice_result(sound_fd, &work_result);
        if (ret < 0) {
            perror("Error reading voice result");
            break;
        }

        if (work_result != 0x00) {
            printf("Voice command detected: 0x%02X\n", work_result);
            
            if (work_result == 0x01) {  // 生成菜单
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                pthread_cond_signal(&menu_cond);
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            } 
            else if (work_result == 0x04) {  // 生成特定菜单
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                global_user_preferences = strdup("减肥");
                pthread_cond_signal(&deep_menu_cond);
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            }
            else if (work_result == 0x02) {  // 打开制冷
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                cold_work();
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            }
            else if (work_result == 0x03) {  // 关闭制冷
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                cold_stop();
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            }
            else if (work_result == 0x06) {  // 查询菜品
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                char* last_food = history_food();
                his_send(last_food);
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            }
            else if (work_result == 0x05) {  // 关闭制冷
                pthread_mutex_lock(&mutex);
                work_result = 0x00;
                float hum1,temp1;
                int result = aht20_main(&temp1, &hum1);
                if (result == 0) {
                  printf("Temperature: %.2f, Humidity: %.2f\n", temp1, hum1);
                } else {
                  printf("Failed to read data\n");
                }
                aht20_send(temp1, hum1);
                pthread_mutex_unlock(&mutex);
                sleep(20);  // 短暂延迟
            }

            
        }
        usleep(200000);  // 200ms 轮询间隔
    }

cleanup:
    if (sound_fd >= 0) close(sound_fd);
    return NULL;
}

// MQTT 发布线程函数
void* mqtt_thread(void* arg) {
    int state1 = 1;
    bool receive;

    // 初始化GPIO和冷工作
    gpio_int();
    cold_work();

    // 初始化 MQTT 客户端
    init_mqtt_client();

    // 确保初始状态一致
    state1 = cold_read(1);
    start_mqtt_publisher(0, state1 == 1);

    while (1) {
        // 读取传感器状态
        state1 = cold_read(1);

        // 根据传感器状态发布MQTT消息
        if (state1 == 1) {
            start_mqtt_publisher(0, true);
        } else if (state1 == 0) {
            start_mqtt_publisher(0, false);
        }

        // 获取最新的接收状态
        receive = mqtt_receive();

        // 检查状态变化
        if (receive != led_state) {
            if (!receive && led_state) {
                cold_stop();
                led_state = false;
            } else if (receive && !led_state) {
                cold_work();
                led_state = true;
            }
        }

        // 添加一个小的延迟以避免CPU占用过高
        sleep(1); // 1秒延迟
    }

    // 清理 MQTT 客户端
    cleanup_mqtt_client();

    return NULL; // 返回NULL以符合void*类型
}
  
  
// 查找菜单并发送到数据库的线程函数
void* menu_thread(void* arg) {
    while (1) {
        // 等待菜单生成信号
        pthread_mutex_lock(&mutex);
        pthread_cond_wait(&menu_cond, &mutex);
        pthread_mutex_unlock(&mutex);
        
        printf("Generating standard menu...\n");
        
        char* category = find_food(NULL);
        if (category) {
            printf("Recognized category: %s\n", category);
        } else {
            printf("Failed to recognize category\n");
            category = strdup("unknown");
        }
        
        char* check_result = check_food(NULL);
        if (check_result) {
            printf("Food check result: %s\n", check_result);
            menu_send(category, check_result);
            menu_write(category, check_result);
            sql_read("menu");
        } else {
            check_result = strdup("unknown");
        }
        start_mqtt_publisher(1, true);
        
        // 清理资源
        free(category);
        if (strcmp(check_result, "error") != 0) free(check_result);
        remove(GARBAGE_FILE);
        
        // 避免连续调用占用资源
        sleep(1);
    }
    return NULL;
}

int main(int argc, char* argv[]) {
    pthread_t voice_tid, menu_tid, deep_menu_tid, mqtt_tid;
    
    // Python 初始化
    python_init();
    PyThreadState* main_tstate = PyEval_SaveThread();

    // 创建线程
    printf("Creating threads...\n");
    pthread_create(&voice_tid, NULL, get_voice_thread, NULL);
    pthread_create(&menu_tid, NULL, menu_thread, NULL);
    pthread_create(&deep_menu_tid, NULL, deep_menu_thread, NULL);
    if (pthread_create(&mqtt_tid, NULL, mqtt_thread, NULL) != 0) {
        perror("Failed to create MQTT thread");
        exit(EXIT_FAILURE);
    }
    
    // 等待线程结束
    pthread_join(voice_tid, NULL);
    pthread_join(menu_tid, NULL);
    pthread_join(deep_menu_tid, NULL);
    pthread_join(mqtt_tid, NULL);
    
    // 清理资源
    PyEval_RestoreThread(main_tstate);
    food_final();
    Py_Finalize();
    
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&menu_cond);
    pthread_cond_destroy(&deep_menu_cond);
    
    printf("Exiting main program\n");
    return 0;
}



